import { toJS, observable, action } from 'mobx';
import { WeaForm } from 'comsMobx';
import { message, Modal } from 'antd';
import { WeaTools } from 'ecCom';
import { WeaSwitch } from 'comsMobx';
import { Button } from 'antd';
import * as Fctt from '../components/constants/BaseFormConstant';

const comTypes = WeaTools.types;
const getKey = WeaTools.getKey;
import { WeaLocaleProvider } from 'ecCom';

const getLabel = WeaLocaleProvider.getLabel;
export default class BaseFormStore {
    @observable componentProps;
    @observable viewTop = false;
    @observable loading = false;
    @observable form = {};
    @observable titleName = '';
    @observable titleIcon = '';
    @observable rightMenus = [];
    @observable formItemGroups = [];
    @observable subTables = [];
    @observable customDatas = {};
    @observable verified = false;
    @observable status = '';
    @observable errorMsg = '';
    @observable showShareDiolog = false;
    @observable sellchanceId='';
    @observable sellchanceName='';
    @observable userId='';
    initData(componentProps) {

    }

    getFormData(componentInitCallBack) {

    }

    @action
    componentWillMount = (componentProps) => {
      this.componentProps = componentProps;
      this.initData(componentProps);
    }

    @action
    componentDidMount = (objTable) => {
      this.objTable = objTable;
      this.loading = true;
      this.getFormData(this.componentInitCallBack);
    }

    @action
    componentInitCallBack = (data) => {
      this.loading = false;
      this.verified = true;
      this.status = data.status;
      if (this.status == 'success') {
        const content = data.datas;
        this.rightMenus = content.rightMenus;
        this.formItemGroups = content.formItemGroups;
        this.subTables = content.subTables;// 获取子表
        this.customDatas = content.customDatas;
        this.sellchanceId = content.customDatas.sellchanceId;
        this.sellchanceName = content.customDatas.subject;
        this.userId = content.customDatas.loginid;
        if (this.viewTop) {
          this.titleName = content.titleName;
          this.titleIcon = content.titleIcon;
        }
        this.form = new WeaForm();
        // 初始化表单组件
        this.form.initFormFields(content.formItemGroups);
      } else if (data.hasright) {
        this.errorMsg = data.msgcode;
      } else {
        this.errorMsg = '对不起，您暂时没有权限！';
      }
    }

    @action
    componentWillUnmount = () => {
      this.loading = false;
      this.titleName = '';
      this.titleIcon = '';
      this.verified = false;
      this.status = '';
      this.errorMsg = '';
      this.form = {};
      this.formItemGroups = [];
      this.subTables = [];
      this.rightMenus = [];
      this.customDatas = {};
    }
    // 点击分享，显示分享界面
    shareShareDialogOnCard = (bool) => {
      this.showShareDiolog = bool;
    }
    getRightMenus() {
      const { rightMenus, customDatas } = this;
      const that = this;
      const btnArr = [];
      rightMenus && rightMenus.length > 0 && rightMenus.map((m) => {
        btnArr.push({
          key: m.type,
          icon: <i className={m.menuIcon} />,
          content: m.menuName,
          disabled: this.loading,
          onClick: (key) => {
            if (key == Fctt.BTN_SAVE) {
              that.doSaveCheck();
            } else if (key == Fctt.BTN_SHARE) {
              that.shareShareDialogOnCard(true);
            } else {
              that.rightMenuClick(key);
            }
          },
        });
      });
      const tagsList = toJS(customDatas).tagsList;
      tagsList && tagsList.length > 0 && tagsList.map((m) => {
        btnArr.push({
          key: m.key,
          icon: <i className={'icon-coms-link'} />,
          content: m.title,
          disabled: this.loading,
          onClick: (key) => {
            this.componentProps.tabStore.extendHandle(m.key, m.title, m.linkurl, m.shortname);
          },
        });
      });
      return btnArr;
    }

    getTopButtons() {
      const { rightMenus } = this;
      const that = this;
      const btnArr = [];
      rightMenus && rightMenus.length > 0 && rightMenus.map((m) => {
        m.isTop == '1' && btnArr.length < 4 && btnArr.push(
          <Button
            ecId={`${this && this.props && this.props.ecId || ''}_Button@ihonum@${m.type}`}
            type="primary"
            disabled={this.loading}
            onClick={() => {
              const fn = m.menuFun.indexOf('this') >= 0 ? `${m.menuFun.split('this')[0]})` : m.menuFun;
              if (m.type == Fctt.BTN_SAVE) {
                that.doSaveCheck();
              } else {
                that.rightMenuClick(m.type);
              }
            }}
          >
            {m.menuName}
          </Button>,
        );
      });
      const btnArrCustom = this.getTopButtonsCustom();
      return btnArrCustom.concat(btnArr);
    }

    getTopButtonsCustom() {
      const btnArr = [];
      return btnArr;
    }

    doSaveCheck = () => {
      // 检查主表
      this.form.validateForm().then((obj) => {
        let f = true;
        const requestParams = this.form.getFormParams();
        if (obj.isValid) {
          // 检查可能性
          if (requestParams.probability) {
            if (requestParams.probability <= 0 || requestParams.probability > 1) {
              f = false;
              Modal.warning({
                title: getLabel(15172, '系统提示'),
                content: getLabel(15241, '请输入0～1之间的数'),
                okText: getLabel(33703, '确定'),
              });
              return;
            }
          }

          // 检查子表
          f = this.objTable.refs.table.showErrors();
          // console.log(f);
        } else {
          f = false;
          obj.showErrors();
        }
        if (f) {
          requestParams.subTables = JSON.stringify(this.subTables);

          this.doSave(requestParams, this.doSaveCallBack);
        } else {
        }
      });
    }

    doSave(requestParams, doSaveCallBack) {
      // this.loading = true;
      this.doSaveData(requestParams, doSaveCallBack);
    }

    doSaveData(requestParams, doSaveCallBack) {

    }

    doSaveCallBack = (data) => {
      this.loading = false;
    }

    getFieldProps(fieldName) {
      const formItemGroups = toJS(this.formItemGroups);
      for (let i = 0; i < formItemGroups.length; i++) {
        const c = formItemGroups[i];
        const fields = c.items;
        for (let j = 0; j < fields.length; j++) {
          if (fields[j].domkey[0] == fieldName) {
            return fields[j];
          }
        }
      }
      return null;
    }

    getFieldValue(fieldName) {
      const requestParams = this.form.getFormParams();
      for (const name in requestParams) {
        if (fieldName == name) {
          return requestParams[name];
        }
      }
    }

    getFieldValueOld(fieldName) {
      const formItemGroups = this.formItemGroups;
      for (let i = 0; i < formItemGroups.length; i++) {
        const items = formItemGroups[i].items;
        for (let j = 0; j < items.length; j++) {
          const item = items[j];
          const name = item.domkey[0];
          if (fieldName == name) {
            return item.value;
          }
        }
      }
    }

    setFieldValueOld(fieldName, fieldValue, attachMentDatas) {
      const formItemGroups = this.formItemGroups;
      for (let i = 0; i < formItemGroups.length; i++) {
        const items = formItemGroups[i].items;
        for (let j = 0; j < items.length; j++) {
          const item = items[j];
          const name = item.domkey[0];
          const formItemType = item.formItemType;
          if (fieldName == name) {
            item.value = fieldValue;
            if (formItemType == 'UPLOAD') {
              item.datas = attachMentDatas;
            }
          }
        }
      }
    }

    formFieldUpdate(k, v) {
      try {
        const fieldObj = {};
        fieldObj[k] = { value: v };
        this.form.updateFields(fieldObj, false);
      } catch (error) {
      }
    }

    formFieldChange(fieldObj) {

    }

    formFieldBlur(fieldObj) {

    }

    setSubTables(obj) {
      this.subTables = obj;
    }

    reDefineField(field) {
      return field;
    }

    rightMenuClick(key) {

    }

    tableDataChange(datas) {

    }
}
